package conf

import (
	"fmt"

	"chainmaker.org/chainmaker/smarteditor/cache"
	"chainmaker.org/chainmaker/smarteditor/db"
	"github.com/jinzhu/gorm"
)

type UserContractScanned struct {
	UserId     string `gorm:"index:idx_id"`
	HasScanned bool
}

func (*UserContractScanned) TableName() string {
	return "user_contract_scanned"
}

func GenerateUseScannedKey(userId string) string {
	return fmt.Sprintf("scanned_%s", userId)
}

// CheckUserHasScanned 检查一下该用户是否已经读取过历史的部署信息
func CheckUserHasScanned(userId string) (bool, error) {
	deKey := GenerateUseScannedKey(userId)
	_, ok := cache.GlobalUserCache.Get(deKey)
	//log.Debugf("CheckUserHasScanned deKey %s ,ok %+v", deKey, ok)
	if ok {
		return true, nil
	}
	var retD UserContractScanned
	err := db.GlobalDB.Model(&UserContractScanned{}).Where("user_id = ?", userId).First(&retD).Error
	if err != nil {
		if gorm.IsRecordNotFoundError(err) {
			return false, nil
		}
		log.Errorf("CheckUserHasScanned userId %s failed %s", userId, err.Error())
		return false, err
	}
	//log.Debugf("CheckUserHasScanned deKey %s ,retD %+v ",deKey,retD)
	cache.GlobalUserCache.Add(deKey, struct{}{})
	return true, nil
}

// SaveUserHasDeployed 记录该用户已经写入了deployinfo信息
func SaveUserHasScanned(userId string) error {
	deKey := GenerateUseScannedKey(userId)
	err := db.GlobalDB.Create(UserContractScanned{UserId: userId, HasScanned: true}).Error
	if err != nil {
		log.Errorf("SaveUserHasScanned userId %s,failed %s", userId, err.Error())
		return err
	}
	cache.GlobalUserCache.Add(deKey, struct{}{})
	return nil
}
